package com.pengli.mytools.ui.webView;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.pengli.mytools.MyApplication;
import com.pengli.mytools.R;
import com.pengli.mytools.beans.po.URLData;

import java.time.Duration;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MyWebViewActivity extends Activity {

    @BindView(R.id.my_webview)
    WebView webView;
    @BindView(R.id.video_view)
    FrameLayout videoview;// 全屏时视频加载view

    private Boolean islandscape = false;//true表示此时是横屏，false表示此时竖屏。
    private xWebChromeClient xwebchromeclient;
    private WebChromeClient.CustomViewCallback xCustomViewCallback;

    private long exitTime = 0;
    private URLData urldata;
    private Thread thread;
    private String tag;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉应用标题
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);

        MyApplication.getInstance().addActivity(this);

        urldata = (URLData) getIntent().getSerializableExtra("urldata");

        initWebSettings();
        loadUrl(urldata.getUrl());
    }

    private void loadUrl(String urlString) {
        webView.loadUrl(urlString);//加载url

//        if (urldata.getUrlIconImgUrl().isEmpty()) {
//            thread = new Thread(new Runnable() {
//                @Override
//                public void run() {
//                    String urlIcon = JsoupUtil.getUrlIcon(urlString);
//                    URLDataDao urlDataDao = GreenDaoDBController.getDaoSession().getURLDataDao();
//                    urldata.setUrlIconImgUrl(urlIcon);
//                    urlDataDao.update(urldata);
//                    //更新后删除缓存数据库信息
//                    urlDataDao.detachAll();
//                }
//            });
//            thread.start();
//        }

    }

    @Override
    public void onBackPressed() {
        //网页逐级返回
        if (webView.canGoBack()) {
            webView.goBack();
        } else {
            if ((System.currentTimeMillis() - exitTime) > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出网页",
                        Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                super.onBackPressed();
            }
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //返回按钮退出全屏
        if (keyCode == KeyEvent.KEYCODE_BACK) {//点击返回按钮
            if (islandscape) {//是否全屏
                //全屏时按返回键执行退出全屏
                xwebchromeclient.onHideCustomView();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //释放资源
        webView.destroy();
        webView = null;
    }

    private void initWebSettings() {
        webView.addJavascriptInterface(new JsObject(), "jsObject");//添加js绑定桥 这样html的js就能调用客户端代码
        xwebchromeclient = new xWebChromeClient();
        webView.setWebChromeClient(xwebchromeclient);
        webView.setWebViewClient(new xWebViewClientent());
        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据
         * setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放
         * setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小
         * setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体
         * setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式
         * setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);//允许使用js

        /**
         * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
         * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
         * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
         * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
         */
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.

        webSettings.setJavaScriptEnabled(true);
        //支持屏幕缩放、是否支持变焦
        webSettings.setSupportZoom(true);
        webSettings.setBuiltInZoomControls(true);// 隐藏缩放按钮
        //不显示webview缩放按钮
        webSettings.setDisplayZoomControls(false);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        webSettings.setUseWideViewPort(true);// 可任意比例缩放
        webSettings.setLoadWithOverviewMode(true);// setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式。
        webSettings.setSavePassword(true);
        webSettings.setSaveFormData(true);// 保存表单数据
        webSettings.setGeolocationEnabled(true);// 启用地理定位
//        webSettings.setGeolocationDatabasePath("/data/data/org.itri.html5webview/databases/");// 设置定位的数据库路径
        webSettings.setDomStorageEnabled(true);
    }

    /**
     * 当横竖屏切换时会调用该方法
     */
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        Log.i("testwebview", "=====<<<  onConfigurationChanged  >>>=====");
        //重写旋转时方法，不销毁activity
        super.onConfigurationChanged(newConfig);
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.i("webview", "   现在是横屏1");
            islandscape = true;
        } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
            Log.i("webview", "   现在是竖屏1");
            islandscape = false;
        }
    }


    /**
     * 自定义WebChromeClient
     * 处理Javascript的对话框、网站图标、网站标题以及网页加载进度等
     */
    public class xWebChromeClient extends WebChromeClient {
        private Bitmap xdefaltvideo;
        private View videoLoadingProgress;

        @Override
        //播放网络视频时全屏会被调用的方法
        public void onShowCustomView(View view, WebChromeClient.CustomViewCallback callback) {
            switchScreen();
            webView.setVisibility(View.GONE);
            videoview.setVisibility(View.VISIBLE);
            videoview.addView(view);
            xCustomViewCallback = callback;
            super.onShowCustomView(view, callback);
        }


        @Override
        //视频播放退出全屏会被调用的
        public void onHideCustomView() {
            switchScreen();
            if (xCustomViewCallback != null) {
                xCustomViewCallback.onCustomViewHidden();
            }
            webView.setVisibility(View.VISIBLE);
            videoview.removeAllViews();
            videoview.setVisibility(View.GONE);
            super.onHideCustomView();
        }



        //视频加载添加默认图标
        @Override
        public Bitmap getDefaultVideoPoster() {
            //Log.i(LOGTAG, "here in on getDefaultVideoPoster");
            if (xdefaltvideo == null) {
                xdefaltvideo = BitmapFactory.decodeResource(
                        getResources(), R.mipmap.videoicon);
            }
            return xdefaltvideo;
        }

//        //视频加载时进程loading
//        @Override
//        public View getVideoLoadingProgressView() {
//            if (videoLoadingProgress == null) {
//                LayoutInflater inflater = LayoutInflater.from(MyWebViewActivity.this);
//                videoLoadingProgress = inflater.inflate(R.layout.video_loading_progress, null);
//            }
//            return videoLoadingProgress;
//        }

        //不支持js的alert弹窗，需要自己监听然后通过dialog弹窗
        @Override
        public boolean onJsAlert(WebView webView, String url, String message, JsResult result) {
            AlertDialog.Builder localBuilder = new AlertDialog.Builder(webView.getContext());
            localBuilder.setMessage(message).setPositiveButton("确定", null);
            localBuilder.setCancelable(false);
            localBuilder.create().show();
            //注意:
            //必须要这一句代码:result.confirm()表示:
            //处理结果为确定状态同时唤醒WebCore线程
            //否则不能继续点击按钮
            result.confirm();
            return true;
        }

//        //获取网页标题
//        @Override
//        public void onReceivedTitle(WebView view, String title) {
//            super.onReceivedTitle(view, title);
//            Log.i("ansen", "网页标题:" + title);
//        }

        //当WebView进度改变时更新窗口进度
//        @Override
//        public void onProgressChanged(WebView view, int newProgress) {
//            progressBar.setProgress(newProgress);
//        }

    }


    /**
     * 自定义WebViewClient
     * 处理各种通知、请求等事件
     *
     * @author
     */
    public class xWebViewClientent extends WebViewClient {

        //webview加载完成时调用
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            //注入全屏js
            tag = getTagByUrl(url);//获取视频控件的标签名
            //html中视频控件全屏js：根据标签名获取视频全屏按钮，设置点击事件，通过js绑定桥jsObject调用本地java全屏函数
            String js = "javascript:document.getElementsByClassName('" + tag + "')[0].addEventListener('click',function(){" +
                    "jsObject.fullscreen();" +
                    "return false;" +
                    "});";
            view.loadUrl(js);
        }

        //网页加载拦截处理
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            Log.i("pengli", "拦截url:" + url);
            if (url.equals("http://www.google.com/")) {
                Toast.makeText(MyWebViewActivity.this, "国内不能访问google,拦截该url", Toast.LENGTH_LONG).show();
                return true;//表示我已经处理过了
            }
            return super.shouldOverrideUrlLoading(view, url);
        }

    }


    private class JsObject {
        //js调用本地代码
        @JavascriptInterface
        public void fullscreen() {
            //监听特殊网站的用户点击全屏按钮
            switchScreen();
        }
        //java调用js
        public void javaCallJS(String method, String parameter) {
            webView.loadUrl("javascript:" + method + "('" + parameter + "')");
        }
    }


    //不同网站的全屏按钮设置了不同标签,根据网站url获取标签tag，用于手动触发注入的js,调用全屏函数
    public static String getTagByUrl(String url) {
        if (url.contains("qq")) {
            return "tvp_fullscreen_button"; // http://m.v.qq.com
        } else if (url.contains("youku")) {
            return "x-zoomin";              // http://www.youku.com
        } else if (url.contains("bilibili")) {
            return "icon-widescreen";       // http://www.bilibili.com/mobile/index.html
        } else if (url.contains("acfun")) {
            return "controller-btn-fullscreen"; //http://m.acfun.tv   无效
        } else if (url.contains("le")) {
            return "hv_ico_screen";         // http://m.le.com  无效
        }
        return "";
    }
    //横竖屏切换
    private void switchScreen() {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } else {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        }
    }

}
